import { FromOptionsProp } from "../interface";

export const useInput = (model: any) => {
  let useInputFocus = ref(true);
  const modelFocus: any = reactive({});

  // 修正值小数范围
  const correctionInputValue = (item: FromOptionsProp) => {
    const { prop, correctionParams } = item;
    const { digit, correctionMethod } = correctionParams || {};

    if (!correctionParams) return;
    nextTick(() => {
      const value = model.value[prop];
      const index = value.indexOf(".");
      if (index !== -1 && value.length >= index + digit + 2) {
        model.value[prop] = parseFloat(value).toFixed(digit);
      }
      correctionMethod && correctionMethod(model.value);
    });
  };

  const inputFocus = item => {
    if (!useInputFocus.value) return;

    let value = "";
    const v = model.value[item.prop];

    if (!v) return;

    value = JSON.parse(JSON.stringify(v));

    modelFocus[item.prop] = false;
    useInputFocus.value = false;
    model.value[item.prop] = " ";

    nextTick(() => {
      modelFocus[item.prop] = true;
      setTimeout(() => {
        model.value[item.prop] = value;
        useInputFocus.value = true;
      }, 100);
    });
  };
  return {
    modelFocus,
    correctionInputValue,
    inputFocus
  };
};
